{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "52df7352",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 循环神经网络的从零开始实现\n",
    ":label:`sec_rnn_scratch`\n",
    "\n",
    "本节将根据 :numref:`sec_rnn`中的描述，\n",
    "从头开始基于循环神经网络实现字符级语言模型。\n",
    "这样的模型将在H.G.Wells的时光机器数据集上训练。\n",
    "和前面 :numref:`sec_language_model`中介绍过的一样，\n",
    "我们先读取数据集。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dafdcbcb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:01.555032Z",
     "iopub.status.busy": "2023-08-18T07:18:01.554199Z",
     "iopub.status.idle": "2023-08-18T07:18:04.803287Z",
     "shell.execute_reply": "2023-08-18T07:18:04.802073Z"
    },
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import math\n",
    "import torch\n",
    "from torch import nn\n",
    "from torch.nn import functional as F\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "be4f5d93",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:04.809116Z",
     "iopub.status.busy": "2023-08-18T07:18:04.808214Z",
     "iopub.status.idle": "2023-08-18T07:18:05.026750Z",
     "shell.execute_reply": "2023-08-18T07:18:05.025592Z"
    },
    "origin_pos": 5,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "batch_size, num_steps = 32, 35\n",
    "train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80db8a1f",
   "metadata": {
    "origin_pos": 7
   },
   "source": [
    "## [**独热编码**]\n",
    "\n",
    "回想一下，在`train_iter`中，每个词元都表示为一个数字索引，\n",
    "将这些索引直接输入神经网络可能会使学习变得困难。\n",
    "我们通常将每个词元表示为更具表现力的特征向量。\n",
    "最简单的表示称为*独热编码*（one-hot encoding），\n",
    "它在 :numref:`subsec_classification-problem`中介绍过。\n",
    "\n",
    "简言之，将每个索引映射为相互不同的单位向量：\n",
    "假设词表中不同词元的数目为$N$（即`len(vocab)`），\n",
    "词元索引的范围为$0$到$N-1$。\n",
    "如果词元的索引是整数$i$，\n",
    "那么我们将创建一个长度为$N$的全$0$向量，\n",
    "并将第$i$处的元素设置为$1$。\n",
    "此向量是原始词元的一个独热向量。\n",
    "索引为$0$和$2$的独热向量如下所示：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c5725a77",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:05.032457Z",
     "iopub.status.busy": "2023-08-18T07:18:05.031682Z",
     "iopub.status.idle": "2023-08-18T07:18:05.042971Z",
     "shell.execute_reply": "2023-08-18T07:18:05.041878Z"
    },
    "origin_pos": 9,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "         0, 0, 0, 0],\n",
       "        [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "         0, 0, 0, 0]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "F.one_hot(torch.tensor([0, 2]), len(vocab))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5d08204",
   "metadata": {
    "origin_pos": 12
   },
   "source": [
    "我们每次采样的(**小批量数据形状是二维张量：\n",
    "（批量大小，时间步数）。**)\n",
    "`one_hot`函数将这样一个小批量数据转换成三维张量，\n",
    "张量的最后一个维度等于词表大小（`len(vocab)`）。\n",
    "我们经常转换输入的维度，以便获得形状为\n",
    "（时间步数，批量大小，词表大小）的输出。\n",
    "这将使我们能够更方便地通过最外层的维度，\n",
    "一步一步地更新小批量数据的隐状态。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "60a49de8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:05.047886Z",
     "iopub.status.busy": "2023-08-18T07:18:05.047143Z",
     "iopub.status.idle": "2023-08-18T07:18:05.054936Z",
     "shell.execute_reply": "2023-08-18T07:18:05.053897Z"
    },
    "origin_pos": 14,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([5, 2, 28])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.arange(10).reshape((2, 5))\n",
    "F.one_hot(X.T, 28).shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32469879",
   "metadata": {
    "origin_pos": 17
   },
   "source": [
    "## 初始化模型参数\n",
    "\n",
    "接下来，我们[**初始化循环神经网络模型的模型参数**]。\n",
    "隐藏单元数`num_hiddens`是一个可调的超参数。\n",
    "当训练语言模型时，输入和输出来自相同的词表。\n",
    "因此，它们具有相同的维度，即词表的大小。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a8ad7abe",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:05.059740Z",
     "iopub.status.busy": "2023-08-18T07:18:05.059023Z",
     "iopub.status.idle": "2023-08-18T07:18:05.067363Z",
     "shell.execute_reply": "2023-08-18T07:18:05.066318Z"
    },
    "origin_pos": 19,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def get_params(vocab_size, num_hiddens, device):\n",
    "    num_inputs = num_outputs = vocab_size\n",
    "\n",
    "    def normal(shape):\n",
    "        return torch.randn(size=shape, device=device) * 0.01\n",
    "\n",
    "    # 隐藏层参数\n",
    "    W_xh = normal((num_inputs, num_hiddens))\n",
    "    W_hh = normal((num_hiddens, num_hiddens))\n",
    "    b_h = torch.zeros(num_hiddens, device=device)\n",
    "    # 输出层参数\n",
    "    W_hq = normal((num_hiddens, num_outputs))\n",
    "    b_q = torch.zeros(num_outputs, device=device)\n",
    "    # 附加梯度\n",
    "    params = [W_xh, W_hh, b_h, W_hq, b_q]\n",
    "    for param in params:\n",
    "        param.requires_grad_(True)\n",
    "    return params"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "037e51a5",
   "metadata": {
    "origin_pos": 22
   },
   "source": [
    "## 循环神经网络模型\n",
    "\n",
    "为了定义循环神经网络模型，\n",
    "我们首先需要[**一个`init_rnn_state`函数在初始化时返回隐状态**]。\n",
    "这个函数的返回是一个张量，张量全用0填充，\n",
    "形状为（批量大小，隐藏单元数）。\n",
    "在后面的章节中我们将会遇到隐状态包含多个变量的情况，\n",
    "而使用元组可以更容易地处理些。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e310bbed",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:05.072206Z",
     "iopub.status.busy": "2023-08-18T07:18:05.071312Z",
     "iopub.status.idle": "2023-08-18T07:18:05.076740Z",
     "shell.execute_reply": "2023-08-18T07:18:05.075653Z"
    },
    "origin_pos": 24,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def init_rnn_state(batch_size, num_hiddens, device):\n",
    "    return (torch.zeros((batch_size, num_hiddens), device=device), )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5c7e392",
   "metadata": {
    "origin_pos": 27
   },
   "source": [
    "[**下面的`rnn`函数定义了如何在一个时间步内计算隐状态和输出。**]\n",
    "循环神经网络模型通过`inputs`最外层的维度实现循环，\n",
    "以便逐时间步更新小批量数据的隐状态`H`。\n",
    "此外，这里使用$\\tanh$函数作为激活函数。\n",
    "如 :numref:`sec_mlp`所述，\n",
    "当元素在实数上满足均匀分布时，$\\tanh$函数的平均值为0。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "84a46eb3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:05.081883Z",
     "iopub.status.busy": "2023-08-18T07:18:05.080930Z",
     "iopub.status.idle": "2023-08-18T07:18:05.088343Z",
     "shell.execute_reply": "2023-08-18T07:18:05.087321Z"
    },
    "origin_pos": 29,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def rnn(inputs, state, params):\n",
    "    # inputs的形状：(时间步数量，批量大小，词表大小)\n",
    "    W_xh, W_hh, b_h, W_hq, b_q = params\n",
    "    H, = state\n",
    "    outputs = []\n",
    "    # X的形状：(批量大小，词表大小)\n",
    "    for X in inputs:\n",
    "        H = torch.tanh(torch.mm(X, W_xh) + torch.mm(H, W_hh) + b_h)\n",
    "        Y = torch.mm(H, W_hq) + b_q\n",
    "        outputs.append(Y)\n",
    "    return torch.cat(outputs, dim=0), (H,)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b99d272d",
   "metadata": {
    "origin_pos": 32
   },
   "source": [
    "定义了所有需要的函数之后，接下来我们[**创建一个类来包装这些函数**]，\n",
    "并存储从零开始实现的循环神经网络模型的参数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a45ae30c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:05.093357Z",
     "iopub.status.busy": "2023-08-18T07:18:05.092334Z",
     "iopub.status.idle": "2023-08-18T07:18:05.101515Z",
     "shell.execute_reply": "2023-08-18T07:18:05.100380Z"
    },
    "origin_pos": 34,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class RNNModelScratch: #@save\n",
    "    \"\"\"从零开始实现的循环神经网络模型\"\"\"\n",
    "    def __init__(self, vocab_size, num_hiddens, device,\n",
    "                 get_params, init_state, forward_fn):\n",
    "        self.vocab_size, self.num_hiddens = vocab_size, num_hiddens\n",
    "        self.params = get_params(vocab_size, num_hiddens, device)\n",
    "        self.init_state, self.forward_fn = init_state, forward_fn\n",
    "\n",
    "    def __call__(self, X, state):\n",
    "        X = F.one_hot(X.T, self.vocab_size).type(torch.float32)\n",
    "        return self.forward_fn(X, state, self.params)\n",
    "\n",
    "    def begin_state(self, batch_size, device):\n",
    "        return self.init_state(batch_size, self.num_hiddens, device)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34b19f1b",
   "metadata": {
    "origin_pos": 37
   },
   "source": [
    "让我们[**检查输出是否具有正确的形状**]。\n",
    "例如，隐状态的维数是否保持不变。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "83809e58",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:05.106127Z",
     "iopub.status.busy": "2023-08-18T07:18:05.105766Z",
     "iopub.status.idle": "2023-08-18T07:18:07.615027Z",
     "shell.execute_reply": "2023-08-18T07:18:07.613950Z"
    },
    "origin_pos": 39,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(torch.Size([10, 28]), 1, torch.Size([2, 512]))"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "num_hiddens = 512\n",
    "net = RNNModelScratch(len(vocab), num_hiddens, d2l.try_gpu(), get_params,\n",
    "                      init_rnn_state, rnn)\n",
    "state = net.begin_state(X.shape[0], d2l.try_gpu())\n",
    "Y, new_state = net(X.to(d2l.try_gpu()), state)\n",
    "Y.shape, len(new_state), new_state[0].shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3baefc97",
   "metadata": {
    "origin_pos": 42
   },
   "source": [
    "我们可以看到输出形状是（时间步数$\\times$批量大小，词表大小），\n",
    "而隐状态形状保持不变，即（批量大小，隐藏单元数）。\n",
    "\n",
    "## 预测\n",
    "\n",
    "让我们[**首先定义预测函数来生成`prefix`之后的新字符**]，\n",
    "其中的`prefix`是一个用户提供的包含多个字符的字符串。\n",
    "在循环遍历`prefix`中的开始字符时，\n",
    "我们不断地将隐状态传递到下一个时间步，但是不生成任何输出。\n",
    "这被称为*预热*（warm-up）期，\n",
    "因为在此期间模型会自我更新（例如，更新隐状态），\n",
    "但不会进行预测。\n",
    "预热期结束后，隐状态的值通常比刚开始的初始值更适合预测，\n",
    "从而预测字符并输出它们。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "a98020e1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:07.619431Z",
     "iopub.status.busy": "2023-08-18T07:18:07.619151Z",
     "iopub.status.idle": "2023-08-18T07:18:07.626388Z",
     "shell.execute_reply": "2023-08-18T07:18:07.625321Z"
    },
    "origin_pos": 44,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def predict_ch8(prefix, num_preds, net, vocab, device):  #@save\n",
    "    \"\"\"在prefix后面生成新字符\"\"\"\n",
    "    state = net.begin_state(batch_size=1, device=device)\n",
    "    outputs = [vocab[prefix[0]]]\n",
    "    get_input = lambda: torch.tensor([outputs[-1]], device=device).reshape((1, 1))\n",
    "    for y in prefix[1:]:  # 预热期\n",
    "        _, state = net(get_input(), state)\n",
    "        outputs.append(vocab[y])\n",
    "    for _ in range(num_preds):  # 预测num_preds步\n",
    "        y, state = net(get_input(), state)\n",
    "        outputs.append(int(y.argmax(dim=1).reshape(1)))\n",
    "    return ''.join([vocab.idx_to_token[i] for i in outputs])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "375db47c",
   "metadata": {
    "origin_pos": 47
   },
   "source": [
    "现在我们可以测试`predict_ch8`函数。\n",
    "我们将前缀指定为`time traveller `，\n",
    "并基于这个前缀生成10个后续字符。\n",
    "鉴于我们还没有训练网络，它会生成荒谬的预测结果。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "8ea33551",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:07.630956Z",
     "iopub.status.busy": "2023-08-18T07:18:07.630335Z",
     "iopub.status.idle": "2023-08-18T07:18:07.646754Z",
     "shell.execute_reply": "2023-08-18T07:18:07.645688Z"
    },
    "origin_pos": 48,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'time traveller aaaaaaaaaa'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "predict_ch8('time traveller ', 10, net, vocab, d2l.try_gpu())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "596cfaf3",
   "metadata": {
    "origin_pos": 50
   },
   "source": [
    "## [**梯度裁剪**]\n",
    "\n",
    "对于长度为$T$的序列，我们在迭代中计算这$T$个时间步上的梯度，\n",
    "将会在反向传播过程中产生长度为$\\mathcal{O}(T)$的矩阵乘法链。\n",
    "如 :numref:`sec_numerical_stability`所述，\n",
    "当$T$较大时，它可能导致数值不稳定，\n",
    "例如可能导致梯度爆炸或梯度消失。\n",
    "因此，循环神经网络模型往往需要额外的方式来支持稳定训练。\n",
    "\n",
    "一般来说，当解决优化问题时，我们对模型参数采用更新步骤。\n",
    "假定在向量形式的$\\mathbf{x}$中，\n",
    "或者在小批量数据的负梯度$\\mathbf{g}$方向上。\n",
    "例如，使用$\\eta > 0$作为学习率时，在一次迭代中，\n",
    "我们将$\\mathbf{x}$更新为$\\mathbf{x} - \\eta \\mathbf{g}$。\n",
    "如果我们进一步假设目标函数$f$表现良好，\n",
    "即函数$f$在常数$L$下是*利普希茨连续的*（Lipschitz continuous）。\n",
    "也就是说，对于任意$\\mathbf{x}$和$\\mathbf{y}$我们有：\n",
    "\n",
    "$$|f(\\mathbf{x}) - f(\\mathbf{y})| \\leq L \\|\\mathbf{x} - \\mathbf{y}\\|.$$\n",
    "\n",
    "在这种情况下，我们可以安全地假设：\n",
    "如果我们通过$\\eta \\mathbf{g}$更新参数向量，则\n",
    "\n",
    "$$|f(\\mathbf{x}) - f(\\mathbf{x} - \\eta\\mathbf{g})| \\leq L \\eta\\|\\mathbf{g}\\|,$$\n",
    "\n",
    "这意味着我们不会观察到超过$L \\eta \\|\\mathbf{g}\\|$的变化。\n",
    "这既是坏事也是好事。\n",
    "坏的方面，它限制了取得进展的速度；\n",
    "好的方面，它限制了事情变糟的程度，尤其当我们朝着错误的方向前进时。\n",
    "\n",
    "有时梯度可能很大，从而优化算法可能无法收敛。\n",
    "我们可以通过降低$\\eta$的学习率来解决这个问题。\n",
    "但是如果我们很少得到大的梯度呢？\n",
    "在这种情况下，这种做法似乎毫无道理。\n",
    "一个流行的替代方案是通过将梯度$\\mathbf{g}$投影回给定半径\n",
    "（例如$\\theta$）的球来裁剪梯度$\\mathbf{g}$。\n",
    "如下式：\n",
    "\n",
    "(**$$\\mathbf{g} \\leftarrow \\min\\left(1, \\frac{\\theta}{\\|\\mathbf{g}\\|}\\right) \\mathbf{g}.$$**)\n",
    "\n",
    "通过这样做，我们知道梯度范数永远不会超过$\\theta$，\n",
    "并且更新后的梯度完全与$\\mathbf{g}$的原始方向对齐。\n",
    "它还有一个值得拥有的副作用，\n",
    "即限制任何给定的小批量数据（以及其中任何给定的样本）对参数向量的影响，\n",
    "这赋予了模型一定程度的稳定性。\n",
    "梯度裁剪提供了一个快速修复梯度爆炸的方法，\n",
    "虽然它并不能完全解决问题，但它是众多有效的技术之一。\n",
    "\n",
    "下面我们定义一个函数来裁剪模型的梯度，\n",
    "模型是从零开始实现的模型或由高级API构建的模型。\n",
    "我们在此计算了所有模型参数的梯度的范数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "997a02ea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:07.651414Z",
     "iopub.status.busy": "2023-08-18T07:18:07.650745Z",
     "iopub.status.idle": "2023-08-18T07:18:07.657007Z",
     "shell.execute_reply": "2023-08-18T07:18:07.655964Z"
    },
    "origin_pos": 52,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def grad_clipping(net, theta):  #@save\n",
    "    \"\"\"裁剪梯度\"\"\"\n",
    "    if isinstance(net, nn.Module):\n",
    "        params = [p for p in net.parameters() if p.requires_grad]\n",
    "    else:\n",
    "        params = net.params\n",
    "    norm = torch.sqrt(sum(torch.sum((p.grad ** 2)) for p in params))\n",
    "    if norm > theta:\n",
    "        for param in params:\n",
    "            param.grad[:] *= theta / norm"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "726d638a",
   "metadata": {
    "origin_pos": 55
   },
   "source": [
    "## 训练\n",
    "\n",
    "在训练模型之前，让我们[**定义一个函数在一个迭代周期内训练模型**]。\n",
    "它与我们训练 :numref:`sec_softmax_scratch`模型的方式有三个不同之处。\n",
    "\n",
    "1. 序列数据的不同采样方法（随机采样和顺序分区）将导致隐状态初始化的差异。\n",
    "1. 我们在更新模型参数之前裁剪梯度。\n",
    "   这样的操作的目的是，即使训练过程中某个点上发生了梯度爆炸，也能保证模型不会发散。\n",
    "1. 我们用困惑度来评价模型。如 :numref:`subsec_perplexity`所述，\n",
    "   这样的度量确保了不同长度的序列具有可比性。\n",
    "\n",
    "具体来说，当使用顺序分区时，\n",
    "我们只在每个迭代周期的开始位置初始化隐状态。\n",
    "由于下一个小批量数据中的第$i$个子序列样本\n",
    "与当前第$i$个子序列样本相邻，\n",
    "因此当前小批量数据最后一个样本的隐状态，\n",
    "将用于初始化下一个小批量数据第一个样本的隐状态。\n",
    "这样，存储在隐状态中的序列的历史信息\n",
    "可以在一个迭代周期内流经相邻的子序列。\n",
    "然而，在任何一点隐状态的计算，\n",
    "都依赖于同一迭代周期中前面所有的小批量数据，\n",
    "这使得梯度计算变得复杂。\n",
    "为了降低计算量，在处理任何一个小批量数据之前，\n",
    "我们先分离梯度，使得隐状态的梯度计算总是限制在一个小批量数据的时间步内。\n",
    "\n",
    "当使用随机抽样时，因为每个样本都是在一个随机位置抽样的，\n",
    "因此需要为每个迭代周期重新初始化隐状态。\n",
    "与 :numref:`sec_softmax_scratch`中的\n",
    "`train_epoch_ch3`函数相同，\n",
    "`updater`是更新模型参数的常用函数。\n",
    "它既可以是从头开始实现的`d2l.sgd`函数，\n",
    "也可以是深度学习框架中内置的优化函数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4b5e10db",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:07.661288Z",
     "iopub.status.busy": "2023-08-18T07:18:07.660940Z",
     "iopub.status.idle": "2023-08-18T07:18:07.671838Z",
     "shell.execute_reply": "2023-08-18T07:18:07.670625Z"
    },
    "origin_pos": 57,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "def train_epoch_ch8(net, train_iter, loss, updater, device, use_random_iter):\n",
    "    \"\"\"训练网络一个迭代周期（定义见第8章）\"\"\"\n",
    "    state, timer = None, d2l.Timer()\n",
    "    metric = d2l.Accumulator(2)  # 训练损失之和,词元数量\n",
    "    for X, Y in train_iter:\n",
    "        if state is None or use_random_iter:\n",
    "            # 在第一次迭代或使用随机抽样时初始化state\n",
    "            state = net.begin_state(batch_size=X.shape[0], device=device)\n",
    "        else:\n",
    "            if isinstance(net, nn.Module) and not isinstance(state, tuple):\n",
    "                # state对于nn.GRU是个张量\n",
    "                state.detach_()\n",
    "            else:\n",
    "                # state对于nn.LSTM或对于我们从零开始实现的模型是个张量\n",
    "                for s in state:\n",
    "                    s.detach_()\n",
    "        y = Y.T.reshape(-1)\n",
    "        X, y = X.to(device), y.to(device)\n",
    "        y_hat, state = net(X, state)\n",
    "        l = loss(y_hat, y.long()).mean()\n",
    "        if isinstance(updater, torch.optim.Optimizer):\n",
    "            updater.zero_grad()\n",
    "            l.backward()\n",
    "            grad_clipping(net, 1)\n",
    "            updater.step()\n",
    "        else:\n",
    "            l.backward()\n",
    "            grad_clipping(net, 1)\n",
    "            # 因为已经调用了mean函数\n",
    "            updater(batch_size=1)\n",
    "        metric.add(l * y.numel(), y.numel())\n",
    "    return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59eb7b57",
   "metadata": {
    "origin_pos": 60
   },
   "source": [
    "[**循环神经网络模型的训练函数既支持从零开始实现，\n",
    "也可以使用高级API来实现。**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "3fe4738f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:07.676190Z",
     "iopub.status.busy": "2023-08-18T07:18:07.675912Z",
     "iopub.status.idle": "2023-08-18T07:18:07.684203Z",
     "shell.execute_reply": "2023-08-18T07:18:07.683026Z"
    },
    "origin_pos": 62,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "def train_ch8(net, train_iter, vocab, lr, num_epochs, device,\n",
    "              use_random_iter=False):\n",
    "    \"\"\"训练模型（定义见第8章）\"\"\"\n",
    "    loss = nn.CrossEntropyLoss()\n",
    "    animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',\n",
    "                            legend=['train'], xlim=[10, num_epochs])\n",
    "    # 初始化\n",
    "    if isinstance(net, nn.Module):\n",
    "        updater = torch.optim.SGD(net.parameters(), lr)\n",
    "    else:\n",
    "        updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)\n",
    "    predict = lambda prefix: predict_ch8(prefix, 50, net, vocab, device)\n",
    "    # 训练和预测\n",
    "    for epoch in range(num_epochs):\n",
    "        ppl, speed = train_epoch_ch8(\n",
    "            net, train_iter, loss, updater, device, use_random_iter)\n",
    "        if (epoch + 1) % 10 == 0:\n",
    "            print(predict('time traveller'))\n",
    "            animator.add(epoch + 1, [ppl])\n",
    "    print(f'困惑度 {ppl:.1f}, {speed:.1f} 词元/秒 {str(device)}')\n",
    "    print(predict('time traveller'))\n",
    "    print(predict('traveller'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a744039a",
   "metadata": {
    "origin_pos": 65
   },
   "source": [
    "[**现在，我们训练循环神经网络模型。**]\n",
    "因为我们在数据集中只使用了10000个词元，\n",
    "所以模型需要更多的迭代周期来更好地收敛。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "60e0712a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:18:07.688319Z",
     "iopub.status.busy": "2023-08-18T07:18:07.688050Z",
     "iopub.status.idle": "2023-08-18T07:19:36.858051Z",
     "shell.execute_reply": "2023-08-18T07:19:36.857197Z"
    },
    "origin_pos": 66,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "困惑度 1.0, 67212.6 词元/秒 cuda:0\n",
      "time traveller for so it will be convenient to speak of himwas e\n",
      "travelleryou can show black is white by argument said filby\n"
     ]
    },
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       "  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"262.1875pt\" height=\"180.65625pt\" viewBox=\"0 0 262.1875 180.65625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2023-08-18T07:19:36.820413</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.5.1, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 180.65625 \n",
       "L 262.1875 180.65625 \n",
       "L 262.1875 0 \n",
       "L 0 0 \n",
       "L 0 180.65625 \n",
       "z\n",
       "\" style=\"fill: none\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 50.14375 143.1 \n",
       "L 245.44375 143.1 \n",
       "L 245.44375 7.2 \n",
       "L 50.14375 7.2 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <path d=\"M 86.015179 143.1 \n",
       "L 86.015179 7.2 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_2\">\n",
       "      <defs>\n",
       "       <path id=\"ma75500ca14\" d=\"M 0 0 \n",
       "L 0 3.5 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#ma75500ca14\" x=\"86.015179\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_1\">\n",
       "      <!-- 100 -->\n",
       "      <g transform=\"translate(76.471429 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-31\" d=\"M 794 531 \n",
       "L 1825 531 \n",
       "L 1825 4091 \n",
       "L 703 3866 \n",
       "L 703 4441 \n",
       "L 1819 4666 \n",
       "L 2450 4666 \n",
       "L 2450 531 \n",
       "L 3481 531 \n",
       "L 3481 0 \n",
       "L 794 0 \n",
       "L 794 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \n",
       "Q 1547 4250 1301 3770 \n",
       "Q 1056 3291 1056 2328 \n",
       "Q 1056 1369 1301 889 \n",
       "Q 1547 409 2034 409 \n",
       "Q 2525 409 2770 889 \n",
       "Q 3016 1369 3016 2328 \n",
       "Q 3016 3291 2770 3770 \n",
       "Q 2525 4250 2034 4250 \n",
       "z\n",
       "M 2034 4750 \n",
       "Q 2819 4750 3233 4129 \n",
       "Q 3647 3509 3647 2328 \n",
       "Q 3647 1150 3233 529 \n",
       "Q 2819 -91 2034 -91 \n",
       "Q 1250 -91 836 529 \n",
       "Q 422 1150 422 2328 \n",
       "Q 422 3509 836 4129 \n",
       "Q 1250 4750 2034 4750 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <path d=\"M 125.872321 143.1 \n",
       "L 125.872321 7.2 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#ma75500ca14\" x=\"125.872321\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_2\">\n",
       "      <!-- 200 -->\n",
       "      <g transform=\"translate(116.328571 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \n",
       "L 3431 531 \n",
       "L 3431 0 \n",
       "L 469 0 \n",
       "L 469 531 \n",
       "Q 828 903 1448 1529 \n",
       "Q 2069 2156 2228 2338 \n",
       "Q 2531 2678 2651 2914 \n",
       "Q 2772 3150 2772 3378 \n",
       "Q 2772 3750 2511 3984 \n",
       "Q 2250 4219 1831 4219 \n",
       "Q 1534 4219 1204 4116 \n",
       "Q 875 4013 500 3803 \n",
       "L 500 4441 \n",
       "Q 881 4594 1212 4672 \n",
       "Q 1544 4750 1819 4750 \n",
       "Q 2544 4750 2975 4387 \n",
       "Q 3406 4025 3406 3419 \n",
       "Q 3406 3131 3298 2873 \n",
       "Q 3191 2616 2906 2266 \n",
       "Q 2828 2175 2409 1742 \n",
       "Q 1991 1309 1228 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <path d=\"M 165.729464 143.1 \n",
       "L 165.729464 7.2 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#ma75500ca14\" x=\"165.729464\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_3\">\n",
       "      <!-- 300 -->\n",
       "      <g transform=\"translate(156.185714 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \n",
       "Q 3050 2419 3304 2112 \n",
       "Q 3559 1806 3559 1356 \n",
       "Q 3559 666 3084 287 \n",
       "Q 2609 -91 1734 -91 \n",
       "Q 1441 -91 1130 -33 \n",
       "Q 819 25 488 141 \n",
       "L 488 750 \n",
       "Q 750 597 1062 519 \n",
       "Q 1375 441 1716 441 \n",
       "Q 2309 441 2620 675 \n",
       "Q 2931 909 2931 1356 \n",
       "Q 2931 1769 2642 2001 \n",
       "Q 2353 2234 1838 2234 \n",
       "L 1294 2234 \n",
       "L 1294 2753 \n",
       "L 1863 2753 \n",
       "Q 2328 2753 2575 2939 \n",
       "Q 2822 3125 2822 3475 \n",
       "Q 2822 3834 2567 4026 \n",
       "Q 2313 4219 1838 4219 \n",
       "Q 1578 4219 1281 4162 \n",
       "Q 984 4106 628 3988 \n",
       "L 628 4550 \n",
       "Q 988 4650 1302 4700 \n",
       "Q 1616 4750 1894 4750 \n",
       "Q 2613 4750 3031 4423 \n",
       "Q 3450 4097 3450 3541 \n",
       "Q 3450 3153 3228 2886 \n",
       "Q 3006 2619 2597 2516 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-33\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <path d=\"M 205.586607 143.1 \n",
       "L 205.586607 7.2 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#ma75500ca14\" x=\"205.586607\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_4\">\n",
       "      <!-- 400 -->\n",
       "      <g transform=\"translate(196.042857 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \n",
       "L 825 1625 \n",
       "L 2419 1625 \n",
       "L 2419 4116 \n",
       "z\n",
       "M 2253 4666 \n",
       "L 3047 4666 \n",
       "L 3047 1625 \n",
       "L 3713 1625 \n",
       "L 3713 1100 \n",
       "L 3047 1100 \n",
       "L 3047 0 \n",
       "L 2419 0 \n",
       "L 2419 1100 \n",
       "L 313 1100 \n",
       "L 313 1709 \n",
       "L 2253 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-34\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <path d=\"M 245.44375 143.1 \n",
       "L 245.44375 7.2 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#ma75500ca14\" x=\"245.44375\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_5\">\n",
       "      <!-- 500 -->\n",
       "      <g transform=\"translate(235.9 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \n",
       "L 3169 4666 \n",
       "L 3169 4134 \n",
       "L 1269 4134 \n",
       "L 1269 2991 \n",
       "Q 1406 3038 1543 3061 \n",
       "Q 1681 3084 1819 3084 \n",
       "Q 2600 3084 3056 2656 \n",
       "Q 3513 2228 3513 1497 \n",
       "Q 3513 744 3044 326 \n",
       "Q 2575 -91 1722 -91 \n",
       "Q 1428 -91 1123 -41 \n",
       "Q 819 9 494 109 \n",
       "L 494 744 \n",
       "Q 775 591 1075 516 \n",
       "Q 1375 441 1709 441 \n",
       "Q 2250 441 2565 725 \n",
       "Q 2881 1009 2881 1497 \n",
       "Q 2881 1984 2565 2268 \n",
       "Q 2250 2553 1709 2553 \n",
       "Q 1456 2553 1204 2497 \n",
       "Q 953 2441 691 2322 \n",
       "L 691 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_6\">\n",
       "     <!-- epoch -->\n",
       "     <g transform=\"translate(132.565625 171.376563)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \n",
       "L 3597 1613 \n",
       "L 953 1613 \n",
       "Q 991 1019 1311 708 \n",
       "Q 1631 397 2203 397 \n",
       "Q 2534 397 2845 478 \n",
       "Q 3156 559 3463 722 \n",
       "L 3463 178 \n",
       "Q 3153 47 2828 -22 \n",
       "Q 2503 -91 2169 -91 \n",
       "Q 1331 -91 842 396 \n",
       "Q 353 884 353 1716 \n",
       "Q 353 2575 817 3079 \n",
       "Q 1281 3584 2069 3584 \n",
       "Q 2775 3584 3186 3129 \n",
       "Q 3597 2675 3597 1894 \n",
       "z\n",
       "M 3022 2063 \n",
       "Q 3016 2534 2758 2815 \n",
       "Q 2500 3097 2075 3097 \n",
       "Q 1594 3097 1305 2825 \n",
       "Q 1016 2553 972 2059 \n",
       "L 3022 2063 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \n",
       "L 1159 -1331 \n",
       "L 581 -1331 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2969 \n",
       "Q 1341 3281 1617 3432 \n",
       "Q 1894 3584 2278 3584 \n",
       "Q 2916 3584 3314 3078 \n",
       "Q 3713 2572 3713 1747 \n",
       "Q 3713 922 3314 415 \n",
       "Q 2916 -91 2278 -91 \n",
       "Q 1894 -91 1617 61 \n",
       "Q 1341 213 1159 525 \n",
       "z\n",
       "M 3116 1747 \n",
       "Q 3116 2381 2855 2742 \n",
       "Q 2594 3103 2138 3103 \n",
       "Q 1681 3103 1420 2742 \n",
       "Q 1159 2381 1159 1747 \n",
       "Q 1159 1113 1420 752 \n",
       "Q 1681 391 2138 391 \n",
       "Q 2594 391 2855 752 \n",
       "Q 3116 1113 3116 1747 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \n",
       "Q 1497 3097 1228 2736 \n",
       "Q 959 2375 959 1747 \n",
       "Q 959 1119 1226 758 \n",
       "Q 1494 397 1959 397 \n",
       "Q 2419 397 2687 759 \n",
       "Q 2956 1122 2956 1747 \n",
       "Q 2956 2369 2687 2733 \n",
       "Q 2419 3097 1959 3097 \n",
       "z\n",
       "M 1959 3584 \n",
       "Q 2709 3584 3137 3096 \n",
       "Q 3566 2609 3566 1747 \n",
       "Q 3566 888 3137 398 \n",
       "Q 2709 -91 1959 -91 \n",
       "Q 1206 -91 779 398 \n",
       "Q 353 888 353 1747 \n",
       "Q 353 2609 779 3096 \n",
       "Q 1206 3584 1959 3584 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \n",
       "L 3122 2828 \n",
       "Q 2878 2963 2633 3030 \n",
       "Q 2388 3097 2138 3097 \n",
       "Q 1578 3097 1268 2742 \n",
       "Q 959 2388 959 1747 \n",
       "Q 959 1106 1268 751 \n",
       "Q 1578 397 2138 397 \n",
       "Q 2388 397 2633 464 \n",
       "Q 2878 531 3122 666 \n",
       "L 3122 134 \n",
       "Q 2881 22 2623 -34 \n",
       "Q 2366 -91 2075 -91 \n",
       "Q 1284 -91 818 406 \n",
       "Q 353 903 353 1747 \n",
       "Q 353 2603 823 3093 \n",
       "Q 1294 3584 2113 3584 \n",
       "Q 2378 3584 2631 3529 \n",
       "Q 2884 3475 3122 3366 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-65\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-70\" x=\"61.523438\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" x=\"125\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-63\" x=\"186.181641\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-68\" x=\"241.162109\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <path d=\"M 50.14375 122.454581 \n",
       "L 245.44375 122.454581 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_12\">\n",
       "      <defs>\n",
       "       <path id=\"m582285a84b\" d=\"M 0 0 \n",
       "L -3.5 0 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m582285a84b\" x=\"50.14375\" y=\"122.454581\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_7\">\n",
       "      <!-- 2.5 -->\n",
       "      <g transform=\"translate(27.240625 126.2538)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \n",
       "L 1344 794 \n",
       "L 1344 0 \n",
       "L 684 0 \n",
       "L 684 794 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_13\">\n",
       "      <path d=\"M 50.14375 97.932543 \n",
       "L 245.44375 97.932543 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_14\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m582285a84b\" x=\"50.14375\" y=\"97.932543\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_8\">\n",
       "      <!-- 5.0 -->\n",
       "      <g transform=\"translate(27.240625 101.731762)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_15\">\n",
       "      <path d=\"M 50.14375 73.410505 \n",
       "L 245.44375 73.410505 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_16\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m582285a84b\" x=\"50.14375\" y=\"73.410505\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_9\">\n",
       "      <!-- 7.5 -->\n",
       "      <g transform=\"translate(27.240625 77.209724)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-37\" d=\"M 525 4666 \n",
       "L 3525 4666 \n",
       "L 3525 4397 \n",
       "L 1831 0 \n",
       "L 1172 0 \n",
       "L 2766 4134 \n",
       "L 525 4134 \n",
       "L 525 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-37\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_17\">\n",
       "      <path d=\"M 50.14375 48.888467 \n",
       "L 245.44375 48.888467 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_18\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m582285a84b\" x=\"50.14375\" y=\"48.888467\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_10\">\n",
       "      <!-- 10.0 -->\n",
       "      <g transform=\"translate(20.878125 52.687686)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"127.246094\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_5\">\n",
       "     <g id=\"line2d_19\">\n",
       "      <path d=\"M 50.14375 24.366429 \n",
       "L 245.44375 24.366429 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_20\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m582285a84b\" x=\"50.14375\" y=\"24.366429\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_11\">\n",
       "      <!-- 12.5 -->\n",
       "      <g transform=\"translate(20.878125 28.165647)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-32\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"127.246094\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_12\">\n",
       "     <!-- perplexity -->\n",
       "     <g transform=\"translate(14.798437 100.276562)rotate(-90)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \n",
       "Q 2534 3019 2420 3045 \n",
       "Q 2306 3072 2169 3072 \n",
       "Q 1681 3072 1420 2755 \n",
       "Q 1159 2438 1159 1844 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1341 3275 1631 3429 \n",
       "Q 1922 3584 2338 3584 \n",
       "Q 2397 3584 2469 3576 \n",
       "Q 2541 3569 2628 3553 \n",
       "L 2631 2963 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-78\" d=\"M 3513 3500 \n",
       "L 2247 1797 \n",
       "L 3578 0 \n",
       "L 2900 0 \n",
       "L 1881 1375 \n",
       "L 863 0 \n",
       "L 184 0 \n",
       "L 1544 1831 \n",
       "L 300 3500 \n",
       "L 978 3500 \n",
       "L 1906 2253 \n",
       "L 2834 3500 \n",
       "L 3513 3500 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \n",
       "L 1178 3500 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 3500 \n",
       "z\n",
       "M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 4134 \n",
       "L 603 4134 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \n",
       "L 1172 3500 \n",
       "L 2356 3500 \n",
       "L 2356 3053 \n",
       "L 1172 3053 \n",
       "L 1172 1153 \n",
       "Q 1172 725 1289 603 \n",
       "Q 1406 481 1766 481 \n",
       "L 2356 481 \n",
       "L 2356 0 \n",
       "L 1766 0 \n",
       "Q 1100 0 847 248 \n",
       "Q 594 497 594 1153 \n",
       "L 594 3053 \n",
       "L 172 3053 \n",
       "L 172 3500 \n",
       "L 594 3500 \n",
       "L 594 4494 \n",
       "L 1172 4494 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-79\" d=\"M 2059 -325 \n",
       "Q 1816 -950 1584 -1140 \n",
       "Q 1353 -1331 966 -1331 \n",
       "L 506 -1331 \n",
       "L 506 -850 \n",
       "L 844 -850 \n",
       "Q 1081 -850 1212 -737 \n",
       "Q 1344 -625 1503 -206 \n",
       "L 1606 56 \n",
       "L 191 3500 \n",
       "L 800 3500 \n",
       "L 1894 763 \n",
       "L 2988 3500 \n",
       "L 3597 3500 \n",
       "L 2059 -325 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-70\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"63.476562\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-72\" x=\"125\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-70\" x=\"166.113281\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6c\" x=\"229.589844\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"257.373047\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-78\" x=\"317.146484\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" x=\"376.326172\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-74\" x=\"404.109375\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-79\" x=\"443.318359\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"line2d_21\">\n",
       "    <path d=\"M 50.14375 13.377273 \n",
       "L 54.129464 43.350149 \n",
       "L 58.115179 53.115171 \n",
       "L 62.100893 58.852743 \n",
       "L 66.086607 62.537584 \n",
       "L 70.072321 66.497195 \n",
       "L 74.058036 68.964635 \n",
       "L 78.04375 70.629984 \n",
       "L 82.029464 72.971361 \n",
       "L 86.015179 74.373165 \n",
       "L 90.000893 77.683226 \n",
       "L 93.986607 80.011156 \n",
       "L 97.972321 83.395311 \n",
       "L 101.958036 85.072362 \n",
       "L 105.94375 89.041998 \n",
       "L 109.929464 93.443468 \n",
       "L 113.915179 99.425029 \n",
       "L 117.900893 105.007337 \n",
       "L 121.886607 111.951181 \n",
       "L 125.872321 117.321032 \n",
       "L 129.858036 120.765318 \n",
       "L 133.84375 124.423533 \n",
       "L 137.829464 127.368408 \n",
       "L 141.815179 129.50798 \n",
       "L 145.800893 130.95189 \n",
       "L 149.786607 132.189668 \n",
       "L 153.772321 132.868554 \n",
       "L 157.758036 133.685833 \n",
       "L 161.74375 133.937264 \n",
       "L 165.729464 133.674318 \n",
       "L 169.715179 134.723396 \n",
       "L 173.700893 135.490549 \n",
       "L 177.686607 136.26968 \n",
       "L 181.672321 136.063133 \n",
       "L 185.658036 136.69623 \n",
       "L 189.64375 135.896478 \n",
       "L 193.629464 135.154041 \n",
       "L 197.615179 135.671014 \n",
       "L 201.600893 136.517208 \n",
       "L 205.586607 136.720643 \n",
       "L 209.572321 136.814831 \n",
       "L 213.558036 136.703534 \n",
       "L 217.54375 136.738584 \n",
       "L 221.529464 136.742116 \n",
       "L 225.515179 136.796472 \n",
       "L 229.500893 136.738296 \n",
       "L 233.486607 136.457172 \n",
       "L 237.472321 136.922727 \n",
       "L 241.458036 136.730109 \n",
       "L 245.44375 136.79664 \n",
       "\" clip-path=\"url(#pc4e2661320)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 50.14375 143.1 \n",
       "L 50.14375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 245.44375 143.1 \n",
       "L 245.44375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 50.14375 143.1 \n",
       "L 245.44375 143.1 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 50.14375 7.2 \n",
       "L 245.44375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"legend_1\">\n",
       "    <g id=\"patch_7\">\n",
       "     <path d=\"M 183.16875 29.878125 \n",
       "L 238.44375 29.878125 \n",
       "Q 240.44375 29.878125 240.44375 27.878125 \n",
       "L 240.44375 14.2 \n",
       "Q 240.44375 12.2 238.44375 12.2 \n",
       "L 183.16875 12.2 \n",
       "Q 181.16875 12.2 181.16875 14.2 \n",
       "L 181.16875 27.878125 \n",
       "Q 181.16875 29.878125 183.16875 29.878125 \n",
       "z\n",
       "\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n",
       "    </g>\n",
       "    <g id=\"line2d_22\">\n",
       "     <path d=\"M 185.16875 20.298437 \n",
       "L 195.16875 20.298437 \n",
       "L 205.16875 20.298437 \n",
       "\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n",
       "    </g>\n",
       "    <g id=\"text_13\">\n",
       "     <!-- train -->\n",
       "     <g transform=\"translate(213.16875 23.798437)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \n",
       "Q 1497 1759 1228 1600 \n",
       "Q 959 1441 959 1056 \n",
       "Q 959 750 1161 570 \n",
       "Q 1363 391 1709 391 \n",
       "Q 2188 391 2477 730 \n",
       "Q 2766 1069 2766 1631 \n",
       "L 2766 1759 \n",
       "L 2194 1759 \n",
       "z\n",
       "M 3341 1997 \n",
       "L 3341 0 \n",
       "L 2766 0 \n",
       "L 2766 531 \n",
       "Q 2569 213 2275 61 \n",
       "Q 1981 -91 1556 -91 \n",
       "Q 1019 -91 701 211 \n",
       "Q 384 513 384 1019 \n",
       "Q 384 1609 779 1909 \n",
       "Q 1175 2209 1959 2209 \n",
       "L 2766 2209 \n",
       "L 2766 2266 \n",
       "Q 2766 2663 2505 2880 \n",
       "Q 2244 3097 1772 3097 \n",
       "Q 1472 3097 1187 3025 \n",
       "Q 903 2953 641 2809 \n",
       "L 641 3341 \n",
       "Q 956 3463 1253 3523 \n",
       "Q 1550 3584 1831 3584 \n",
       "Q 2591 3584 2966 3190 \n",
       "Q 3341 2797 3341 1997 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-74\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-72\" x=\"39.208984\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-61\" x=\"80.322266\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" x=\"141.601562\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"169.384766\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"pc4e2661320\">\n",
       "   <rect x=\"50.14375\" y=\"7.2\" width=\"195.3\" height=\"135.9\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<Figure size 252x180 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "num_epochs, lr = 500, 1\n",
    "train_ch8(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f058da1",
   "metadata": {
    "origin_pos": 68
   },
   "source": [
    "[**最后，让我们检查一下使用随机抽样方法的结果。**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "e672f727",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T07:19:36.861442Z",
     "iopub.status.busy": "2023-08-18T07:19:36.861161Z",
     "iopub.status.idle": "2023-08-18T07:20:58.207471Z",
     "shell.execute_reply": "2023-08-18T07:20:58.206663Z"
    },
    "origin_pos": 69,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "困惑度 1.5, 65222.3 词元/秒 cuda:0\n",
      "time traveller held in his hand was a glitteringmetallic framewo\n",
      "traveller but now you begin to seethe object of my investig\n"
     ]
    },
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       "  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"262.1875pt\" height=\"180.65625pt\" viewBox=\"0 0 262.1875 180.65625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2023-08-18T07:20:58.170314</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.5.1, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 180.65625 \n",
       "L 262.1875 180.65625 \n",
       "L 262.1875 0 \n",
       "L 0 0 \n",
       "L 0 180.65625 \n",
       "z\n",
       "\" style=\"fill: none\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 50.14375 143.1 \n",
       "L 245.44375 143.1 \n",
       "L 245.44375 7.2 \n",
       "L 50.14375 7.2 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <path d=\"M 86.015179 143.1 \n",
       "L 86.015179 7.2 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_2\">\n",
       "      <defs>\n",
       "       <path id=\"mfd988fc604\" d=\"M 0 0 \n",
       "L 0 3.5 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#mfd988fc604\" x=\"86.015179\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_1\">\n",
       "      <!-- 100 -->\n",
       "      <g transform=\"translate(76.471429 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-31\" d=\"M 794 531 \n",
       "L 1825 531 \n",
       "L 1825 4091 \n",
       "L 703 3866 \n",
       "L 703 4441 \n",
       "L 1819 4666 \n",
       "L 2450 4666 \n",
       "L 2450 531 \n",
       "L 3481 531 \n",
       "L 3481 0 \n",
       "L 794 0 \n",
       "L 794 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \n",
       "Q 1547 4250 1301 3770 \n",
       "Q 1056 3291 1056 2328 \n",
       "Q 1056 1369 1301 889 \n",
       "Q 1547 409 2034 409 \n",
       "Q 2525 409 2770 889 \n",
       "Q 3016 1369 3016 2328 \n",
       "Q 3016 3291 2770 3770 \n",
       "Q 2525 4250 2034 4250 \n",
       "z\n",
       "M 2034 4750 \n",
       "Q 2819 4750 3233 4129 \n",
       "Q 3647 3509 3647 2328 \n",
       "Q 3647 1150 3233 529 \n",
       "Q 2819 -91 2034 -91 \n",
       "Q 1250 -91 836 529 \n",
       "Q 422 1150 422 2328 \n",
       "Q 422 3509 836 4129 \n",
       "Q 1250 4750 2034 4750 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <path d=\"M 125.872321 143.1 \n",
       "L 125.872321 7.2 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mfd988fc604\" x=\"125.872321\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_2\">\n",
       "      <!-- 200 -->\n",
       "      <g transform=\"translate(116.328571 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \n",
       "L 3431 531 \n",
       "L 3431 0 \n",
       "L 469 0 \n",
       "L 469 531 \n",
       "Q 828 903 1448 1529 \n",
       "Q 2069 2156 2228 2338 \n",
       "Q 2531 2678 2651 2914 \n",
       "Q 2772 3150 2772 3378 \n",
       "Q 2772 3750 2511 3984 \n",
       "Q 2250 4219 1831 4219 \n",
       "Q 1534 4219 1204 4116 \n",
       "Q 875 4013 500 3803 \n",
       "L 500 4441 \n",
       "Q 881 4594 1212 4672 \n",
       "Q 1544 4750 1819 4750 \n",
       "Q 2544 4750 2975 4387 \n",
       "Q 3406 4025 3406 3419 \n",
       "Q 3406 3131 3298 2873 \n",
       "Q 3191 2616 2906 2266 \n",
       "Q 2828 2175 2409 1742 \n",
       "Q 1991 1309 1228 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <path d=\"M 165.729464 143.1 \n",
       "L 165.729464 7.2 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mfd988fc604\" x=\"165.729464\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_3\">\n",
       "      <!-- 300 -->\n",
       "      <g transform=\"translate(156.185714 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \n",
       "Q 3050 2419 3304 2112 \n",
       "Q 3559 1806 3559 1356 \n",
       "Q 3559 666 3084 287 \n",
       "Q 2609 -91 1734 -91 \n",
       "Q 1441 -91 1130 -33 \n",
       "Q 819 25 488 141 \n",
       "L 488 750 \n",
       "Q 750 597 1062 519 \n",
       "Q 1375 441 1716 441 \n",
       "Q 2309 441 2620 675 \n",
       "Q 2931 909 2931 1356 \n",
       "Q 2931 1769 2642 2001 \n",
       "Q 2353 2234 1838 2234 \n",
       "L 1294 2234 \n",
       "L 1294 2753 \n",
       "L 1863 2753 \n",
       "Q 2328 2753 2575 2939 \n",
       "Q 2822 3125 2822 3475 \n",
       "Q 2822 3834 2567 4026 \n",
       "Q 2313 4219 1838 4219 \n",
       "Q 1578 4219 1281 4162 \n",
       "Q 984 4106 628 3988 \n",
       "L 628 4550 \n",
       "Q 988 4650 1302 4700 \n",
       "Q 1616 4750 1894 4750 \n",
       "Q 2613 4750 3031 4423 \n",
       "Q 3450 4097 3450 3541 \n",
       "Q 3450 3153 3228 2886 \n",
       "Q 3006 2619 2597 2516 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-33\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <path d=\"M 205.586607 143.1 \n",
       "L 205.586607 7.2 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mfd988fc604\" x=\"205.586607\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_4\">\n",
       "      <!-- 400 -->\n",
       "      <g transform=\"translate(196.042857 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \n",
       "L 825 1625 \n",
       "L 2419 1625 \n",
       "L 2419 4116 \n",
       "z\n",
       "M 2253 4666 \n",
       "L 3047 4666 \n",
       "L 3047 1625 \n",
       "L 3713 1625 \n",
       "L 3713 1100 \n",
       "L 3047 1100 \n",
       "L 3047 0 \n",
       "L 2419 0 \n",
       "L 2419 1100 \n",
       "L 313 1100 \n",
       "L 313 1709 \n",
       "L 2253 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-34\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <path d=\"M 245.44375 143.1 \n",
       "L 245.44375 7.2 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mfd988fc604\" x=\"245.44375\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_5\">\n",
       "      <!-- 500 -->\n",
       "      <g transform=\"translate(235.9 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \n",
       "L 3169 4666 \n",
       "L 3169 4134 \n",
       "L 1269 4134 \n",
       "L 1269 2991 \n",
       "Q 1406 3038 1543 3061 \n",
       "Q 1681 3084 1819 3084 \n",
       "Q 2600 3084 3056 2656 \n",
       "Q 3513 2228 3513 1497 \n",
       "Q 3513 744 3044 326 \n",
       "Q 2575 -91 1722 -91 \n",
       "Q 1428 -91 1123 -41 \n",
       "Q 819 9 494 109 \n",
       "L 494 744 \n",
       "Q 775 591 1075 516 \n",
       "Q 1375 441 1709 441 \n",
       "Q 2250 441 2565 725 \n",
       "Q 2881 1009 2881 1497 \n",
       "Q 2881 1984 2565 2268 \n",
       "Q 2250 2553 1709 2553 \n",
       "Q 1456 2553 1204 2497 \n",
       "Q 953 2441 691 2322 \n",
       "L 691 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_6\">\n",
       "     <!-- epoch -->\n",
       "     <g transform=\"translate(132.565625 171.376563)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \n",
       "L 3597 1613 \n",
       "L 953 1613 \n",
       "Q 991 1019 1311 708 \n",
       "Q 1631 397 2203 397 \n",
       "Q 2534 397 2845 478 \n",
       "Q 3156 559 3463 722 \n",
       "L 3463 178 \n",
       "Q 3153 47 2828 -22 \n",
       "Q 2503 -91 2169 -91 \n",
       "Q 1331 -91 842 396 \n",
       "Q 353 884 353 1716 \n",
       "Q 353 2575 817 3079 \n",
       "Q 1281 3584 2069 3584 \n",
       "Q 2775 3584 3186 3129 \n",
       "Q 3597 2675 3597 1894 \n",
       "z\n",
       "M 3022 2063 \n",
       "Q 3016 2534 2758 2815 \n",
       "Q 2500 3097 2075 3097 \n",
       "Q 1594 3097 1305 2825 \n",
       "Q 1016 2553 972 2059 \n",
       "L 3022 2063 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \n",
       "L 1159 -1331 \n",
       "L 581 -1331 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2969 \n",
       "Q 1341 3281 1617 3432 \n",
       "Q 1894 3584 2278 3584 \n",
       "Q 2916 3584 3314 3078 \n",
       "Q 3713 2572 3713 1747 \n",
       "Q 3713 922 3314 415 \n",
       "Q 2916 -91 2278 -91 \n",
       "Q 1894 -91 1617 61 \n",
       "Q 1341 213 1159 525 \n",
       "z\n",
       "M 3116 1747 \n",
       "Q 3116 2381 2855 2742 \n",
       "Q 2594 3103 2138 3103 \n",
       "Q 1681 3103 1420 2742 \n",
       "Q 1159 2381 1159 1747 \n",
       "Q 1159 1113 1420 752 \n",
       "Q 1681 391 2138 391 \n",
       "Q 2594 391 2855 752 \n",
       "Q 3116 1113 3116 1747 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \n",
       "Q 1497 3097 1228 2736 \n",
       "Q 959 2375 959 1747 \n",
       "Q 959 1119 1226 758 \n",
       "Q 1494 397 1959 397 \n",
       "Q 2419 397 2687 759 \n",
       "Q 2956 1122 2956 1747 \n",
       "Q 2956 2369 2687 2733 \n",
       "Q 2419 3097 1959 3097 \n",
       "z\n",
       "M 1959 3584 \n",
       "Q 2709 3584 3137 3096 \n",
       "Q 3566 2609 3566 1747 \n",
       "Q 3566 888 3137 398 \n",
       "Q 2709 -91 1959 -91 \n",
       "Q 1206 -91 779 398 \n",
       "Q 353 888 353 1747 \n",
       "Q 353 2609 779 3096 \n",
       "Q 1206 3584 1959 3584 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \n",
       "L 3122 2828 \n",
       "Q 2878 2963 2633 3030 \n",
       "Q 2388 3097 2138 3097 \n",
       "Q 1578 3097 1268 2742 \n",
       "Q 959 2388 959 1747 \n",
       "Q 959 1106 1268 751 \n",
       "Q 1578 397 2138 397 \n",
       "Q 2388 397 2633 464 \n",
       "Q 2878 531 3122 666 \n",
       "L 3122 134 \n",
       "Q 2881 22 2623 -34 \n",
       "Q 2366 -91 2075 -91 \n",
       "Q 1284 -91 818 406 \n",
       "Q 353 903 353 1747 \n",
       "Q 353 2603 823 3093 \n",
       "Q 1294 3584 2113 3584 \n",
       "Q 2378 3584 2631 3529 \n",
       "Q 2884 3475 3122 3366 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-65\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-70\" x=\"61.523438\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" x=\"125\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-63\" x=\"186.181641\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-68\" x=\"241.162109\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <path d=\"M 50.14375 124.832177 \n",
       "L 245.44375 124.832177 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_12\">\n",
       "      <defs>\n",
       "       <path id=\"m9bbd36c7ec\" d=\"M 0 0 \n",
       "L -3.5 0 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m9bbd36c7ec\" x=\"50.14375\" y=\"124.832177\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_7\">\n",
       "      <!-- 2.5 -->\n",
       "      <g transform=\"translate(27.240625 128.631396)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \n",
       "L 1344 794 \n",
       "L 1344 0 \n",
       "L 684 0 \n",
       "L 684 794 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_13\">\n",
       "      <path d=\"M 50.14375 99.75196 \n",
       "L 245.44375 99.75196 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_14\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m9bbd36c7ec\" x=\"50.14375\" y=\"99.75196\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_8\">\n",
       "      <!-- 5.0 -->\n",
       "      <g transform=\"translate(27.240625 103.551179)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_15\">\n",
       "      <path d=\"M 50.14375 74.671743 \n",
       "L 245.44375 74.671743 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_16\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m9bbd36c7ec\" x=\"50.14375\" y=\"74.671743\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_9\">\n",
       "      <!-- 7.5 -->\n",
       "      <g transform=\"translate(27.240625 78.470962)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-37\" d=\"M 525 4666 \n",
       "L 3525 4666 \n",
       "L 3525 4397 \n",
       "L 1831 0 \n",
       "L 1172 0 \n",
       "L 2766 4134 \n",
       "L 525 4134 \n",
       "L 525 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-37\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_17\">\n",
       "      <path d=\"M 50.14375 49.591527 \n",
       "L 245.44375 49.591527 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_18\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m9bbd36c7ec\" x=\"50.14375\" y=\"49.591527\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_10\">\n",
       "      <!-- 10.0 -->\n",
       "      <g transform=\"translate(20.878125 53.390745)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"127.246094\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_5\">\n",
       "     <g id=\"line2d_19\">\n",
       "      <path d=\"M 50.14375 24.51131 \n",
       "L 245.44375 24.51131 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_20\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m9bbd36c7ec\" x=\"50.14375\" y=\"24.51131\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_11\">\n",
       "      <!-- 12.5 -->\n",
       "      <g transform=\"translate(20.878125 28.310528)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-32\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"127.246094\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_12\">\n",
       "     <!-- perplexity -->\n",
       "     <g transform=\"translate(14.798437 100.276562)rotate(-90)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \n",
       "Q 2534 3019 2420 3045 \n",
       "Q 2306 3072 2169 3072 \n",
       "Q 1681 3072 1420 2755 \n",
       "Q 1159 2438 1159 1844 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1341 3275 1631 3429 \n",
       "Q 1922 3584 2338 3584 \n",
       "Q 2397 3584 2469 3576 \n",
       "Q 2541 3569 2628 3553 \n",
       "L 2631 2963 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-78\" d=\"M 3513 3500 \n",
       "L 2247 1797 \n",
       "L 3578 0 \n",
       "L 2900 0 \n",
       "L 1881 1375 \n",
       "L 863 0 \n",
       "L 184 0 \n",
       "L 1544 1831 \n",
       "L 300 3500 \n",
       "L 978 3500 \n",
       "L 1906 2253 \n",
       "L 2834 3500 \n",
       "L 3513 3500 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \n",
       "L 1178 3500 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 3500 \n",
       "z\n",
       "M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 4134 \n",
       "L 603 4134 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \n",
       "L 1172 3500 \n",
       "L 2356 3500 \n",
       "L 2356 3053 \n",
       "L 1172 3053 \n",
       "L 1172 1153 \n",
       "Q 1172 725 1289 603 \n",
       "Q 1406 481 1766 481 \n",
       "L 2356 481 \n",
       "L 2356 0 \n",
       "L 1766 0 \n",
       "Q 1100 0 847 248 \n",
       "Q 594 497 594 1153 \n",
       "L 594 3053 \n",
       "L 172 3053 \n",
       "L 172 3500 \n",
       "L 594 3500 \n",
       "L 594 4494 \n",
       "L 1172 4494 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-79\" d=\"M 2059 -325 \n",
       "Q 1816 -950 1584 -1140 \n",
       "Q 1353 -1331 966 -1331 \n",
       "L 506 -1331 \n",
       "L 506 -850 \n",
       "L 844 -850 \n",
       "Q 1081 -850 1212 -737 \n",
       "Q 1344 -625 1503 -206 \n",
       "L 1606 56 \n",
       "L 191 3500 \n",
       "L 800 3500 \n",
       "L 1894 763 \n",
       "L 2988 3500 \n",
       "L 3597 3500 \n",
       "L 2059 -325 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-70\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"63.476562\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-72\" x=\"125\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-70\" x=\"166.113281\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6c\" x=\"229.589844\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"257.373047\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-78\" x=\"317.146484\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" x=\"376.326172\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-74\" x=\"404.109375\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-79\" x=\"443.318359\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"line2d_21\">\n",
       "    <path d=\"M 50.14375 13.377273 \n",
       "L 54.129464 43.747485 \n",
       "L 58.115179 53.077185 \n",
       "L 62.100893 58.811614 \n",
       "L 66.086607 62.233697 \n",
       "L 70.072321 66.381807 \n",
       "L 74.058036 68.973047 \n",
       "L 78.04375 69.63825 \n",
       "L 82.029464 71.888906 \n",
       "L 86.015179 73.958481 \n",
       "L 90.000893 75.075607 \n",
       "L 93.986607 77.749171 \n",
       "L 97.972321 80.289625 \n",
       "L 101.958036 82.887605 \n",
       "L 105.94375 84.446884 \n",
       "L 109.929464 91.224405 \n",
       "L 113.915179 94.832586 \n",
       "L 117.900893 95.589954 \n",
       "L 121.886607 103.035327 \n",
       "L 125.872321 108.20689 \n",
       "L 129.858036 112.504065 \n",
       "L 133.84375 116.605407 \n",
       "L 137.829464 121.522328 \n",
       "L 141.815179 120.771902 \n",
       "L 145.800893 125.316262 \n",
       "L 149.786607 127.410314 \n",
       "L 153.772321 128.847872 \n",
       "L 157.758036 128.024025 \n",
       "L 161.74375 130.817083 \n",
       "L 165.729464 131.02627 \n",
       "L 169.715179 130.745567 \n",
       "L 173.700893 132.596466 \n",
       "L 177.686607 132.674507 \n",
       "L 181.672321 132.550857 \n",
       "L 185.658036 133.524015 \n",
       "L 189.64375 133.554983 \n",
       "L 193.629464 134.703987 \n",
       "L 197.615179 133.719708 \n",
       "L 201.600893 134.734715 \n",
       "L 205.586607 134.386083 \n",
       "L 209.572321 133.987415 \n",
       "L 213.558036 133.916368 \n",
       "L 217.54375 134.359118 \n",
       "L 221.529464 134.003386 \n",
       "L 225.515179 136.248762 \n",
       "L 229.500893 134.301286 \n",
       "L 233.486607 136.922727 \n",
       "L 237.472321 134.76188 \n",
       "L 241.458036 135.075048 \n",
       "L 245.44375 134.379426 \n",
       "\" clip-path=\"url(#pf4c151a5df)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 50.14375 143.1 \n",
       "L 50.14375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 245.44375 143.1 \n",
       "L 245.44375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 50.14375 143.1 \n",
       "L 245.44375 143.1 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 50.14375 7.2 \n",
       "L 245.44375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"legend_1\">\n",
       "    <g id=\"patch_7\">\n",
       "     <path d=\"M 183.16875 29.878125 \n",
       "L 238.44375 29.878125 \n",
       "Q 240.44375 29.878125 240.44375 27.878125 \n",
       "L 240.44375 14.2 \n",
       "Q 240.44375 12.2 238.44375 12.2 \n",
       "L 183.16875 12.2 \n",
       "Q 181.16875 12.2 181.16875 14.2 \n",
       "L 181.16875 27.878125 \n",
       "Q 181.16875 29.878125 183.16875 29.878125 \n",
       "z\n",
       "\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n",
       "    </g>\n",
       "    <g id=\"line2d_22\">\n",
       "     <path d=\"M 185.16875 20.298437 \n",
       "L 195.16875 20.298437 \n",
       "L 205.16875 20.298437 \n",
       "\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n",
       "    </g>\n",
       "    <g id=\"text_13\">\n",
       "     <!-- train -->\n",
       "     <g transform=\"translate(213.16875 23.798437)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \n",
       "Q 1497 1759 1228 1600 \n",
       "Q 959 1441 959 1056 \n",
       "Q 959 750 1161 570 \n",
       "Q 1363 391 1709 391 \n",
       "Q 2188 391 2477 730 \n",
       "Q 2766 1069 2766 1631 \n",
       "L 2766 1759 \n",
       "L 2194 1759 \n",
       "z\n",
       "M 3341 1997 \n",
       "L 3341 0 \n",
       "L 2766 0 \n",
       "L 2766 531 \n",
       "Q 2569 213 2275 61 \n",
       "Q 1981 -91 1556 -91 \n",
       "Q 1019 -91 701 211 \n",
       "Q 384 513 384 1019 \n",
       "Q 384 1609 779 1909 \n",
       "Q 1175 2209 1959 2209 \n",
       "L 2766 2209 \n",
       "L 2766 2266 \n",
       "Q 2766 2663 2505 2880 \n",
       "Q 2244 3097 1772 3097 \n",
       "Q 1472 3097 1187 3025 \n",
       "Q 903 2953 641 2809 \n",
       "L 641 3341 \n",
       "Q 956 3463 1253 3523 \n",
       "Q 1550 3584 1831 3584 \n",
       "Q 2591 3584 2966 3190 \n",
       "Q 3341 2797 3341 1997 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-74\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-72\" x=\"39.208984\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-61\" x=\"80.322266\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" x=\"141.601562\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"169.384766\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"pf4c151a5df\">\n",
       "   <rect x=\"50.14375\" y=\"7.2\" width=\"195.3\" height=\"135.9\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<Figure size 252x180 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "net = RNNModelScratch(len(vocab), num_hiddens, d2l.try_gpu(), get_params,\n",
    "                      init_rnn_state, rnn)\n",
    "train_ch8(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu(),\n",
    "          use_random_iter=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11df14f3",
   "metadata": {
    "origin_pos": 72
   },
   "source": [
    "从零开始实现上述循环神经网络模型，\n",
    "虽然有指导意义，但是并不方便。\n",
    "在下一节中，我们将学习如何改进循环神经网络模型。\n",
    "例如，如何使其实现地更容易，且运行速度更快。\n",
    "\n",
    "## 小结\n",
    "\n",
    "* 我们可以训练一个基于循环神经网络的字符级语言模型，根据用户提供的文本的前缀生成后续文本。\n",
    "* 一个简单的循环神经网络语言模型包括输入编码、循环神经网络模型和输出生成。\n",
    "* 循环神经网络模型在训练以前需要初始化状态，不过随机抽样和顺序划分使用初始化方法不同。\n",
    "* 当使用顺序划分时，我们需要分离梯度以减少计算量。\n",
    "* 在进行任何预测之前，模型通过预热期进行自我更新（例如，获得比初始值更好的隐状态）。\n",
    "* 梯度裁剪可以防止梯度爆炸，但不能应对梯度消失。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 尝试说明独热编码等价于为每个对象选择不同的嵌入表示。\n",
    "1. 通过调整超参数（如迭代周期数、隐藏单元数、小批量数据的时间步数、学习率等）来改善困惑度。\n",
    "    * 困惑度可以降到多少？\n",
    "    * 用可学习的嵌入表示替换独热编码，是否会带来更好的表现？\n",
    "    * 如果用H.G.Wells的其他书作为数据集时效果如何，\n",
    "      例如[*世界大战*](http://www.gutenberg.org/ebooks/36)？\n",
    "1. 修改预测函数，例如使用采样，而不是选择最有可能的下一个字符。\n",
    "    * 会发生什么？\n",
    "    * 调整模型使之偏向更可能的输出，例如，当$\\alpha > 1$，从$q(x_t \\mid x_{t-1}, \\ldots, x_1) \\propto P(x_t \\mid x_{t-1}, \\ldots, x_1)^\\alpha$中采样。\n",
    "1. 在不裁剪梯度的情况下运行本节中的代码会发生什么？\n",
    "1. 更改顺序划分，使其不会从计算图中分离隐状态。运行时间会有变化吗？困惑度呢？\n",
    "1. 用ReLU替换本节中使用的激活函数，并重复本节中的实验。我们还需要梯度裁剪吗？为什么？\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c810dbc6",
   "metadata": {
    "origin_pos": 74,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/2103)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}